package fatboy.communication;

import java.io.IOException;


public class BasicProxy implements Basic {
	/*
	 * 
	 */
	private ObjectID id;
	private static final long serialVersionUID = 1L;
	private Location location;
	/**
	 * 
	 * @param other ObjectID of remote Object this will point to 
	 */
	public BasicProxy(ObjectID other){
		id = new ObjectID(other);
		location = new RemoteLocation((ObjectID)other);
//		location = other.location;
	}
	/**
	 * 
	 * @param other ObjectID of saved file
	 * @param filePath String of the file path to the saved object
	 */
	public BasicProxy(ObjectID other, String filePath){
		id = new ObjectID(other);
		location = new FileLocation(filePath);
	}
	/**
	 * 
	 * @return ObjectID of this object
	 */
	public ObjectID getID(){
		return id;
	}
	
	/*public void Constructor(String initialString)
	{
		String meth = "BasicLocal";
		Object[] params = new Object[1];
		params[0] = initialString;
		Class[] types = new Class[1];
		types[0] = String.class;
		createCommand(id,meth,types,params,false);
	}*/
	
	/***
	*	@return the Varible stored inside the Basic
	*
	*	@throws IOException if a proxy object has trouble connecting remotely
	*
	***/
	public String getVar(){
		String ret = null;
		String meth = "getVar";
		ret = (String) createCommand(id, meth, new Class[0], new Object[0], true);
		return ret;
	}
	/***
	*	@param in that is to replace old varible. 
	*/ 
	public void setVar(String in){			
		String meth = "setVar";
		Object[] params = {in};
		Class[] types = {String.class};
		createCommand(id,meth,types,params,false);		
	}
	
	public int add(int first, int second)
	{
		String meth = "add";
		Object[] params = {first, second};
		Class[] types = {int.class, int.class};
		return (Integer) createCommand(id, meth, types, params, true);
	}
	
	private Object createCommand(ObjectID idIn, String meth, Class<Object>[] types,
			Object[] params, boolean returns){
		Object result = null;
		try {
			Command cmd = new Command(idIn,meth,types,params, BasicLocal.class);
			location.sendCommand(cmd);
			if(cmd.hasReturn()){
				result = location.recieveReturn();
				System.out.println("Server returned: " + result);
			}
			location.close();
		} catch (IOException e) {
			System.out.println("could not access remote file");
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (ClassNotFoundException e) {
			System.out.println("couldn't find class");
			e.printStackTrace();
		}
		return result;
	}
	

}
